package com.example.demo.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DomainUtil {

  private static final String PATTERN_IP = "(\\d*\\.){3}\\d*";

  //获取环境域名
  public static String getDomain(HttpServletRequest request) {
    String serverName = request.getServerName();//localhost
    String contextPath = request.getContextPath();//项目名
    String url;

    Pattern ipPattern = Pattern.compile(PATTERN_IP);
    Matcher matcher = ipPattern.matcher(serverName);
    //判断是本地访问还是通过ip访问
    if (serverName.equals("localhost") || matcher.find()) {
      int serverPort = request.getServerPort();//8080
      if (StringUtils.isEmpty(contextPath)) {
        url = "http://" + serverName + ":" + serverPort;//http://localhost:8080/test
      } else {
        url = "http://" + serverName + ":" + serverPort + contextPath;//http://localhost:8080/test
      }
    } else {
      if (StringUtils.isEmpty(contextPath)) {
        url = "https://" + serverName; //https://xxxx.com
      } else {
        url = "https://" + serverName + ":" + contextPath; //https://xxxx.com
      }
    }
    return url;
  }
}
